package com.quectel.business.dms.application.access.accessor.ieg.impl;

import com.quectel.business.dms.application.ApplicationAccessConf;
import com.quectel.business.dms.application.access.accessor.ieg.AbstractIntelligentEntranceGuardAccessor;
import com.quectel.business.dms.application.access.accessor.ieg.model.DeviceFaceSendCmd;
import com.quectel.business.dms.application.access.accessor.ieg.model.DeviceQrCodeGenCmd;
import com.quectel.business.dms.application.access.basemodel.ApplicationOriginDevice;
import com.quectel.core.module.application.dto.ApplicationDto;
import com.quectel.core.module.device.dto.DeviceCommandTemplateDto;
import com.quectel.core.module.device.dto.DeviceDto;
import com.quectel.core.module.device.service.DeviceTypeService;
import com.quectel.sdk.hikisc.HikISCRequester;
import com.quectel.util.common.MyFileUtils;
import com.quectel.util.kit.StorageKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.http.HttpResponse;
import org.springframework.stereotype.Component;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author rananxin
 * @date 2021/11/29 5:33 下午
 */
@Component
@Slf4j
public class HikEntranceGuardAccessorImpl extends AbstractIntelligentEntranceGuardAccessor {

    @DubboReference
    private DeviceTypeService deviceTypeService;

    public List<AbstractIntelligentEntranceGuardAccessor.AbilityEnum> abilities() {
        return Lists.newArrayList();
    }

    public String getPictures(ApplicationDto applicationDto, String svrIndexCode, String extEventPictureURL) {
        ApplicationAccessConf.TemplateOfHikIscConf templateOfHikIscConf = ApplicationAccessConf.parseExtStr(ApplicationAccessConf.TemplateOfHikIscConf.class, applicationDto.getAccessConf());
        String picturesPath = "/api/acs/v1/event/pictures";
        Map<String, Object> jsonObject = new HashMap<>();
        jsonObject.put("svrIndexCode", svrIndexCode);
        jsonObject.put("picUri", extEventPictureURL);

        HikISCRequester instance = HikISCRequester.getInstance(templateOfHikIscConf.getAk(), templateOfHikIscConf.getSk(), templateOfHikIscConf.getHost());
        HttpResponse httpResponse = null;
        File file = null;
        try {
            httpResponse = instance.postBackHttpResponse(picturesPath, jsonObject);
            if (httpResponse != null
                    && httpResponse.getEntity().getContent() != null
                    && httpResponse.getEntity().getContent().available() > 0) {
                file = MyFileUtils.writeFileToTempDir(httpResponse.getEntity().getContent(), UUID.randomUUID().toString() + ".jpg", true);
                String url = StorageKit.uploadToPublicBucketObtainUrl(file);
                return url;
            } else {
                // 需要关闭海康运管平台图片认证才可成功获取
                File tempDir = MyFileUtils.downloadToTempDir("https://" + templateOfHikIscConf.getHost() + extEventPictureURL, false);
                String upload = StorageKit.uploadToPublicBucketObtainUrl(tempDir);
                return upload;
            }
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            if (file != null && file.exists()) {
                file.delete();
            }
            if (httpResponse instanceof Closeable) {
                try {
                    ((Closeable) httpResponse).close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return null;
    }

    @Override
    public boolean openDoor(List<DeviceDto> doors) {

        return false;
    }

    @Override
    public void authPerson(DeviceFaceSendCmd deviceInfo) {

    }

    @Override
    public String genQrCode(DeviceQrCodeGenCmd deviceQrCodeGenCmd) {
        return null;
    }

    @Override
    public boolean syncOrRegisterDevices(ApplicationDto application, List<ApplicationOriginDevice> devices) {

//        LOGGER.info("海康 同步设备线程开启 appId {} 时间 {}", json.getString("appId"), DateUtils.getCurrentDateStr(DateUtils.FormatType.COMMON));
//
//        List<HikGateDeviceDto> allList = new ArrayList<>();
//
//        String appId = json.getString("appId");
//        String appSecret = json.getString("appSecret");
//        String appUrl = json.getString("appUrl");
//
//        HikIscRestUtils instance = HikIscRestUtils.getInstance(appId, appSecret, appUrl);
//        // 查询门禁设备列表v2
//        String path = "/api/resource/v2/acsDevice/search";
//        List<HikGateDeviceDto> list = new ArrayList<>();
//        int count = 0, total = 0;
//        Map<String, Integer> queryMap = new HashMap<>();
//        queryMap.put("pageSize", 1000);
//
//        try {
//            do {
//                queryMap.put("pageNo", ++count);
//                String response = instance.post(path, queryMap);
//                try {
//                    JSONObject responseJson = JacksonUtils.parse(response);
//                    JSONObject data = responseJson.getJSONObject("data");
//                    String deivceStr = data.getString("list");
//                    List<HikGateDeviceDto> hikGateDeviceDtos = JSON.parseArray(deivceStr, HikGateDeviceDto.class);
//                    list.addAll(hikGateDeviceDtos);
//                    total = data.getIntValue("total");
//                } catch (Exception e) {
//                    break;
//                }
//
//            } while (total > list.size());
//            threadPool.submit(new GateDeviceDataHandler(appId, list, applicationService, deviceService, deviceTypeService, villageService));
//            allList.addAll(list);
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return allList;

        return false;
    }

    @Override
    public boolean subscribeEvents(ApplicationDto applicationDto) {
        ApplicationAccessConf.TemplateOfHikIscConf templateOfHikIscConf = ApplicationAccessConf.parseExtStr(ApplicationAccessConf.TemplateOfHikIscConf.class, applicationDto.getAccessConf());

        String subPath = "/api/eventService/v1/eventSubscriptionByEventTypes";
        HikISCRequester instance = HikISCRequester.getInstance(templateOfHikIscConf.getAk()
                , templateOfHikIscConf.getSk(), templateOfHikIscConf.getHost());

//        Map<String, List<Integer>> codeArr = HikIscConstants.EventEnum.getCodeArr();
//        for (String path : codeArr.keySet()) {
//            String response = instance.post(subPath, new HashMap<String, Object>() {{
//                put("eventTypes", codeArr.get(path).stream().toArray(Integer[]::new));
//                put("eventDest", templateOfHikIscConf.getUrl());
//            }});
//        }
        return true;
    }

    @Override
    public boolean initApplication(ApplicationDto application) {
        syncOrRegisterDevices(application, null);
        subscribeEvents(application);
        return true;
    }

    @Override
    public boolean sendCmd(DeviceDto deviceDto, DeviceCommandTemplateDto deviceCommandTemplateDto, Map<String, Object> params, Long cmdId) {
        return true;
    }
}
